from sentence_transformers import SentenceTransformer, util
# model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
model = SentenceTransformer('F:/taitanworkplace/paraphrase-multilingual-MiniLM-L12-v2')
def calculate_semantic_similarity(sentence1: str, sentence2: str) -> float:
    """
    计算两个中文句子的语义相似度（余弦相似度）
    参数:
        sentence1 (str): 第一个句子
        sentence2 (str): 第二个句子
    返回:
        float: 语义相似度分数（范围 0~1）
    """
    # 过滤掉空格和换行符
    sentence1 = sentence1.replace(" ", "").replace("\n", "")
    sentence2 = sentence2.replace(" ", "").replace("\n", "")
    if sentence1 == sentence2:
        return 1.0
    # 编码句子为向量
    embedding1 = model.encode(sentence1, convert_to_tensor=True)
    embedding2 = model.encode(sentence2, convert_to_tensor=True)
    # 计算余弦相似度
    cosine_score = util.pytorch_cos_sim(embedding1, embedding2)
    return cosine_score.item()